package cn.com.lsjz.nursemanager.service.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.com.lsjz.commons.utils.EncodeUtils;
import cn.com.lsjz.commons.utils.UpdateTool;
import cn.com.lsjz.nursemanager.model.system.SysUser;
import cn.com.lsjz.nursemanager.model.system.SysUserVsDept;
import cn.com.lsjz.nursemanager.model.system.SysUserVsRole;
import cn.com.lsjz.nursemanager.repository.system.SysUserRepository;
import cn.com.lsjz.nursemanager.repository.system.SysUserVsDeptRepository;
import cn.com.lsjz.nursemanager.repository.system.SysUserVsRoleRepository;

@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserRepository sysUserRepository;

	@Autowired
	private SysUserVsRoleRepository userVsRoleRepository;

	@Autowired
	private SysUserVsDeptRepository userVsDeptRepository;

	private static final String SALT = "lsjz"; // 盐值

	@Override
	public SysUser getUser(String userId, String password) {
		return sysUserRepository.getByUserIdAndPassword(userId, EncodeUtils.md5(SALT + password));
	}

	@Override
	public List<SysUser> loadUserList(String deptCode, String userName) {
		List<SysUser> users = null;
		if (!StringUtils.isEmpty(userName)) { // 不为空,则根据用户名模糊匹配
			users = sysUserRepository.getByUserNameContaining(userName);
		} else if (!StringUtils.isEmpty(deptCode)) { // 不为空，则根据科室号进行查询
			users = sysUserRepository.getByDeptCode(deptCode);
		} else { // 否则，获取所有的用户信息
			users = sysUserRepository.findAll();
		}
		return users;
	}

	@Override
	public SysUser saveUser(SysUser user) {
		user.setCreateTime(new Date());
		user.setActive(1); // 设置默认启用
		user.setPassword(EncodeUtils.md5(SALT + "a")); // 初始密码a
		user = sysUserRepository.save(user);
		user.setUserId(String.valueOf(user.getId() + 1000)); // 处理自动生成ID
		return sysUserRepository.save(user);
	}

	@Override
	public SysUser editUser(SysUser user) {
		SysUser user2 = sysUserRepository.findOne(user.getId());
		UpdateTool.copyNullProperties(user2, user);
		return sysUserRepository.save(user);
	}

	@Override
	public void delUser(Integer id) {
		// 删除用户角色
		sysUserRepository.updateByHql(
				" delete from UserVsRole ur where ur.userId in " + "( select u.userId from User u where u.id = ?1 ) ",
				id);
		// 删除用户科室
		sysUserRepository.updateByHql(
				"delete from UserVsDept ud where ud.userId in " + "( select u.userId from User u where u.id = ?1  )",
				id);
		// 删除用户
		sysUserRepository.delete(id);
	}

	@Override
	public SysUser getUser(Integer id) {
		return sysUserRepository.findOne(id);
	}

	@Override
	public Map<String, Object> getPermission(String userId) {
		Map<String, Object> map = new HashMap<>();
		List<SysUserVsRole> roleList = userVsRoleRepository.getByUserId(userId);
		List<SysUserVsDept> deptList = userVsDeptRepository.getByUserId(userId);
		map.put("roleList", roleList);
		map.put("deptList", deptList);
		return map;
	}

	@Override
	public void savePermission(String userId, String roles, String depts) {
		List<SysUserVsRole> roleList = userVsRoleRepository.getByUserId(userId);
		List<SysUserVsDept> deptList = userVsDeptRepository.getByUserId(userId);
		List<String> roleStrList = new ArrayList<>();
		List<String> deptStrList = new ArrayList<>();
		// 删除
		for (SysUserVsDept userVsDept : deptList) { // 科室
			if (!depts.contains(userVsDept.getDeptCode() + ",")) { // 传入的里面不包含当前，表示这个不需要了
				userVsDeptRepository.delete(userVsDept);
			}
			deptStrList.add(userVsDept.getDeptCode());
		}
		for (SysUserVsRole userVsRole : roleList) { // 角色
			if (!roles.contains(userVsRole.getRoleId() + "id")) {
				userVsRoleRepository.delete(userVsRole);
			}
			roleStrList.add(userVsRole.getRoleId());
		}
		// 新增
		for (String roleId : roles.split(",")) {
			if (!roleStrList.contains(roleId)) {
				SysUserVsRole userVsRole = new SysUserVsRole();
				userVsRole.setRoleId(roleId);
				userVsRole.setUserId(userId);
				userVsRoleRepository.save(userVsRole);
			}
		}
		for (String deptCode : depts.split(",")) {
			if (!deptStrList.contains(deptCode)) {
				SysUserVsDept userVsDept = new SysUserVsDept();
				userVsDept.setUserId(userId);
				userVsDept.setDeptCode(deptCode);
				userVsDeptRepository.save(userVsDept);
			}
		}
	}

	@Override
	public void activeUser(Integer id, Integer active) {
		sysUserRepository.updateByHql(" update User u set u.active = ?1 where u.id = ?2 ", active, id);
	}

	@Override
	public boolean modifyPwd(Integer id, String oldPassword, String newPassword) {
		SysUser user = sysUserRepository.findOne(id);
		if(EncodeUtils.md5(SALT + oldPassword).equals(user.getPassword())) { // 密码匹配
			SysUser user2 = new SysUser();
			UpdateTool.copyNullProperties(user, user2);
			user2.setPassword(EncodeUtils.md5(SALT + newPassword));
			sysUserRepository.save(user2);
			return true;
		}else {
			return false;
		}
	}

}
